package org.deltaset.faces;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.faces.context.FacesContext;

/**
 *
 * @author dmakariev
 */
public abstract class Functions {

    public static boolean isUserInRole(String role) {
        return FacesContext.getCurrentInstance().getExternalContext().isUserInRole(role);
    }

    public static String getHeader(String name) {
        return FacesUtils.getHeader(name);
    }

    public static void setValueExpression(String expression, Object value) {
        FacesUtils.setValueExpression(expression, value);
    }

    public static String loadResourceAsText(String fileName) {
        try {
            if (null == FacesContext.getCurrentInstance().getExternalContext().getResource(fileName)) {
                return "FILE NOT FOUND :" + fileName;
            }
            final InputStream inputStream = FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream(fileName);
            return streamToString(inputStream);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    static String streamToString(InputStream is) throws IOException {
        final StringBuilder sb = new StringBuilder();
        final BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            sb.append(line).append("\n");
        }
        is.close();
        return sb.toString();
    }
}
